package com.blueskything.practice.lesson01;

import java.util.Random;

/**
 * 感知机
 * 线性模型：y=wx-b
 * 理论详见：https://www.bilibili.com/cheese/play/ss17600
 *
 * @since 2024/8/26.
 */
public class PreBody {
    // 参数
    private double w;
    // 偏值
    private double b;
    private double x;
    private double y;
    // 学习率
    private double studyPad = 0.005;

    public PreBody() {
        Random random = new Random();
        w = random.nextDouble();
        b = random.nextDouble();
    }

    /**
     * @param parameter 运算参数(x)
     *
     * @return
     */
    public double insertParameter(double parameter) {
        this.y = w * parameter - b;
        this.x = parameter;
        return y;
    }

    /**
     * 返回误差
     *
     * @param expect 期望值
     */
    public void backError(double expect) {
        double error = (expect - y) * studyPad;
        // w的误差值
        double subW = error * x;
        // b的误差值
        double subB = error * (-1); // -1为参数b的系数
        this.w += subW;
        this.b += subB;
    }

    /**
     * 给定x推测出y
     *
     * @param x
     *
     * @return y
     */
    public double computeResult(double x) {
        return (w * (x) - b);
    }

    @Override
    public String toString() {
        return String.format("y=%s*X %s %s", w, b > 0 ? '+' : '-', Math.abs(b));
    }
}
